<template>
  <aside class="sidebar">
    <div class="sidebar-logo">
      <img src="../../assets/小粉书logo.png" alt="小红书Logo" />
    </div>
    <nav class="sidebar-nav">
      <ul>
        <li
            v-for="menu in menus"
            :key="menu.id"
            @click="goToMenu(menu.id)"
            :class="{ active: menu.id === activeMenu }"
        >
          <span class="icon">{{ menu.icon }}</span>
          <span>{{ menu.label }}</span>
        </li>
      </ul>
    </nav>
    <button class="login-btn" @click="logout">退出账号</button>
  </aside>

  <div class="upload-container">
    <h2>上传帖子</h2>
    <form @submit.prevent="submitPost">
      <div class="form-group">
        <label for="title">标题：</label>
        <input type="text" id="title" v-model="title" required>
      </div>
      <div class="form-group">
        <label for="content">内容：</label>
        <textarea id="content" v-model="content"></textarea>
      </div>
      <div class="form-group">
        <label for="category">分类：</label>
        <select id="category" v-model="category" required>
          <option value="video">视频</option>
          <option value="image">图片</option>
          <option value="text_to_image">文字转图片</option>
        </select>
      </div>
      <div class="form-group">
        <label for="tags">标签：</label>
        <input type="text" id="tags" v-model="tags" placeholder="用#加文字，如#美食#旅行">
      </div>
      <div class="form-group">
        <label for="file">上传图片/视频：</label>
        <input type="file" id="file" @change="handleFileUpload" accept="image/*,video/*" multiple>
        <div class="uploaded-images">
          <div v-for="(media, index) in uploadedMedia" :key="index" class="uploaded-media">
            <img v-if="media.type === 'image'" :src="media.preview" alt="Uploaded Media" class="media-preview">
            <video v-if="media.type === 'video'" :src="media.preview" controls class="media-preview"></video>
            <button @click="removeMedia(index)" class="remove-button">删除</button>
          </div>
        </div>
      </div>
      <div class="form-group">
        <button type="submit" class="submit-button">提交帖子</button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const menus = ref([
  { id: "发现", label: "发现", icon: "🏠" },
  { id: "发布", label: "发布", icon: "➕" },
  { id: "通知", label: "通知", icon: "🔔" },
  { id: "更多", label: "更多", icon: "☰" }
]);
const activeMenu = ref("发现");

const goToMenu = (id: string) => {
  if (id === "发布") {
    router.push("/upload"); // 跳转到上传页面
  } else if (id === "发现") {
    router.push("/recommend");
  } else {
    activeMenu.value = id;
  }
};

function logout() {
  localStorage.removeItem("token");
  router.push("/login");
}

const title = ref<string>("");
const content = ref<string>("");
const category = ref<string>("image"); // 默认分类为图片
const tags = ref<string>(""); // 添加标签字段
const uploadedMedia = ref<{ file: File; preview: string; type: string }[]>([]);

const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files) {
    for (let i = 0; i < target.files.length; i++) {
      const file = target.files[i];
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target) {
          uploadedMedia.value.push({
            file: file,
            preview: e.target.result as string,
            type: file.type.startsWith('image') ? 'image' : 'video'
          });
        }
      };
      reader.readAsDataURL(file);
    }
  }
};

const removeMedia = (index: number) => {
  uploadedMedia.value.splice(index, 1);
};

const submitPost = async () => {
  const formData = new FormData();
  formData.append('title', title.value);
  formData.append('content', content.value);
  formData.append('category', category.value);
  formData.append('tags', tags.value); // 添加标签到表单数据

  // 根据 category 的值检查是否上传了相应的文件
  if (category.value === 'image' && !uploadedMedia.value.some(media => media.type === 'image')) {
    alert('图片文件是必填项');
    return;
  }
  if (category.value === 'video' && !uploadedMedia.value.some(media => media.type === 'video')) {
    alert('视频文件是必填项');
    return;
  }

  uploadedMedia.value.forEach((media, index) => {
    formData.append('file', media.file); // 统一文件字段名称为 'file'
  });

  try {
    const response = await fetch('http://192.168.10.130:5000/content/upload', {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}` // 确保 JWT 格式正确
      }
    });
    const data = await response.json();
    if (response.ok) {
      alert('帖子上传成功');
      router.push('/recommend'); // 跳转到首页
    } else {
      alert(`上传失败：${data.error}`);
    }
  } catch (err) {
    console.error('上传失败', err);
    alert("上传失败，请检查网络连接或联系管理员");
  }
};
</script>

<style scoped>
.upload-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
}

form div {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

input, textarea, select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
  background-color: #fff;
  color: #333;
}

textarea {
  resize: vertical;
}

button {
  padding: 10px 20px;
  background-color: #ff4560;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

button:hover {
  background-color: #e0395c;
}

.uploaded-images {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.uploaded-media {
  position: relative;
  margin-right: 10px;
  margin-bottom: 10px;
}

.media-preview {
  max-width: 100px;
  max-height: 100px;
  border-radius: 4px;
}

.remove-button {
  position: absolute;
  top: 0;
  right: 0;
  padding: 2px 6px;
  background-color: #ff4560;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.remove-button:hover {
  background-color: #e0395c;
}
</style>